package com.example.gokchinesefoodmappcdev.handler;

import com.example.gokchinesefoodmappcdev.util.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义授权异常处理
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    private final static Logger logger = LoggerFactory.getLogger(MyAuthenticationEntryPoint.class);
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        logger.info("===============授权异常===============");
        logger.info(accessDeniedException.getMessage());
        ResultData resultData = ResultData.fail(ResultData.VERIFY_FAIL, "授权失败");
        response.getWriter().println(new ObjectMapper().writeValueAsString(resultData));
    }
}
